#include "stmflash.h"

void WriteFlash(uint32_t addr, uint8_t *buff, int buf_len) {
	int i = 0;
	/* 解锁FLASH */
	HAL_FLASH_Unlock();

	/* 对FLASH烧写 */
	for (i = 0; i < buf_len; i += 4) {
		HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, addr + i,
				*(uint32_t*) (buff + i));
	}

	/* 上锁FLASH */
	HAL_FLASH_Lock();
}

int Erase_page(uint32_t pageaddr, uint32_t num) {
	uint32_t PageError = 0;
	HAL_StatusTypeDef status;
	__disable_irq();
	//清除标志位，经测试 必要！！！
	__HAL_FLASH_CLEAR_FLAG(
			FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR | FLASH_FLAG_OPTVERR | FLASH_FLAG_PGAERR | FLASH_FLAG_BSY);
	HAL_FLASH_Unlock();
	/* 擦除FLASH*/
	FLASH_EraseInitTypeDef FlashSet;
	FlashSet.TypeErase = FLASH_TYPEERASE_PAGES;	//按页擦除
	FlashSet.NbPages = num;  //擦除的页数
//	printf("识别的初始页数:%ld  共删除%ld页\r\n", FlashSet.Page, num);
	/*设置PageError，调用擦除函数*/
	status = HAL_FLASHEx_Erase(&FlashSet, &PageError);
	if (status != HAL_OK) {
		printf("HAL_FLASHEx_Erase  ERROR\r\n");
	}
	printf("Erase sucessfully!\r\n");
	HAL_FLASH_Lock();
	__enable_irq();
	return 1;
}
